package cn.java.test;


import net.sf.json.JSONObject;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * Created by lenovo on 2016/10/20.
 */
//@Controller
public class CodeController {

    private static final String username = "admin123";

    private static final String passwd = "123456";
    /**
     * @param args
     */
    public static void main(String[] args) {
    	StringBuffer sBuffer = new StringBuffer();
		//产生随机验证码
		for(int i = 0; i < 4; i++){
			int k = (int) (10*(Math.random()));
			sBuffer.append(k);
		}
        CodeController qs = new CodeController();
        try {
            qs.send("13100663470", "【注册验证】  验证码:"+ sBuffer +",您正在注册成为交互管理用户，感谢您的支持！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMsg(String phone,String msg,String needstatus,String port,String sendtime) throws Exception{
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://www.qybor.com:8500/shortMessage");
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        NameValuePair[] data ={
                new NameValuePair("username",this.username),
                new NameValuePair("passwd",this.passwd),
                new NameValuePair("phone",phone),
                new NameValuePair("msg",msg),
                new NameValuePair("needstatus",needstatus),
                new NameValuePair("port",port),
                new NameValuePair("sendtime",sendtime)};
        post.setRequestBody(data);
        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        String result = new String(post.getResponseBodyAsString().getBytes());
        System.out.println(result); //打印返回消息状态
        post.releaseConnection();

        Map group2 = (Map) JSONObject.toBean(JSONObject.fromObject(result),Map.class);
        System.out.println(group2.get("batchno"));
        System.out.println(group2.get("respcode"));
        System.out.println(group2.get("respdesc"));
    }
    /**
     * 简单短信发送
     * @param phone 手机号码，多个
     * @param msg
     * @throws Exception
     */
    /*@ResponseBody
    @RequestMapping(value= "/send",method = RequestMethod.POST)*/
    public void send(String phone,String msg) throws Exception{
        this.sendMsg(phone, msg, "true", "", "");
    }
}
